<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文化图片 - 贝壳OC智能应用中心</title>
    <meta name="description" content="文化图片助手，支持连续对话和历史记录">
    <link rel="stylesheet" href="chat-styles.css">
</head>

<body>
    <!-- 返回按钮 -->
    <div class="back-button" onclick="window.location.href='index.html'">
        <span>←</span> 返回首页
    </div>

    <!-- 主容器 -->
    <div class="chat-container">
        <!-- 头部 -->
        <div class="chat-header">
            <div class="chat-title">
                <div class="chat-icon">🎨</div>
                <h1>文化图片助手</h1>
                <div class="chat-status online">在线</div>
            </div>
            <div class="chat-actions">
                <button class="action-btn" onclick="clearHistory()" title="清空历史">
                    <span>🗑️</span>
                </button>
                <button class="action-btn" onclick="exportHistory()" title="导出对话">
                    <span>📤</span>
                </button>
            </div>
        </div>

        <!-- 对话区域 -->
        <div class="chat-messages" id="chatMessages">
            <div class="welcome-message">
                <div class="message bot-message">
                    <div class="message-avatar">🤖</div>
                    <div class="message-content">
                        <div class="message-text">
                            您好！我是文化图片创作助手，专门帮助您根据命题结合沉淀数据生成条漫，提供多样化的创意表达方式，让企业文化传播更加生动有趣。请告诉我您想要创作什么主题的文化图片？
                        </div>
                        <div class="message-time">刚刚</div>
                        <div class="message-actions">
                            <button class="copy-btn" onclick="copyMessage(this)" title="复制消息">
                                <span>📋</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-container">
            <div class="chat-input-wrapper">
                <textarea id="chatInput" placeholder="请输入您想要创作的文化图片主题..." rows="1" onkeydown="handleKeyDown(event)"
                    oninput="autoResize(this); toggleSendButton()"></textarea>
                <button id="sendButton" onclick="sendMessage()" disabled>
                    <span class="send-icon">📤</span>
                </button>
            </div>
            <div class="input-tips">
                <span>按 Enter 发送，Shift + Enter 换行</span>
            </div>
        </div>
    </div>

    <!-- 粒子背景 -->
    <div class="particles-bg" id="particles-js"></div>

    <script src="particles.js"></script>
    <script>
        // 全局变量
        let chatHistory = [];
        let isTyping = false;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function () {
            loadChatHistory();
            setTimeout(initializeParticles, 1000);
        });

        // 初始化粒子背景
        function initializeParticles() {
            try {
                if (typeof particlesJS !== 'undefined') {
                    particlesJS('particles-js', {
                        particles: {
                            number: { value: 20 },
                            color: { value: '#ffffff' },
                            shape: { type: 'circle' },
                            opacity: { value: 0.3 },
                            size: { value: 3 },
                            move: {
                                enable: true,
                                speed: 1,
                                direction: 'none',
                                random: true,
                                straight: false,
                                out_mode: 'out',
                                bounce: false
                            }
                        },
                        interactivity: {
                            detect_on: 'canvas',
                            events: {
                                onhover: { enable: true, mode: 'repulse' },
                                onclick: { enable: true, mode: 'push' },
                                resize: true
                            }
                        },
                        retina_detect: true
                    });
                }
            } catch (error) {
                console.error('粒子背景初始化失败:', error);
            }
        }

        // 处理键盘事件
        function handleKeyDown(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        }

        // 自动调整输入框高度
        function autoResize(textarea) {
            textarea.style.height = 'auto';
            textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
        }

        // 切换发送按钮状态
        function toggleSendButton() {
            const chatInput = document.getElementById('chatInput');
            const sendButton = document.getElementById('sendButton');
            sendButton.disabled = chatInput.value.trim() === '' || isTyping;
        }

        // 发送消息
        async function sendMessage() {
            const chatInput = document.getElementById('chatInput');
            const message = chatInput.value.trim();

            if (message === '' || isTyping) return;

            addMessage(message, 'user');
            chatInput.value = '';
            chatInput.style.height = 'auto';
            toggleSendButton();

            showTypingIndicator();

            try {
                const response = await callCozeAPI(message);
                hideTypingIndicator();
                addMessage(response, 'bot');
            } catch (error) {
                hideTypingIndicator();
                console.error('API调用失败:', error);
                addMessage('抱歉，服务暂时不可用，请稍后再试。', 'bot');
            }
        }

        // 调用扣子API
        async function callCozeAPI(query) {
            const accessToken = 'pat_9Ydl8c51bougw6nBTxUhXbDweMnYKdbkzTSfY9TkMYNbe5ZZ9hNLnzmbHyw3r9zW';
            const botId = '7509711806592761891';
            const apiUrl = 'https://api.coze.cn/open_api/v2/chat';

            const requestBody = {
                bot_id: botId,
                user: 'web_user_' + Date.now(),
                query: query,
                stream: false
            };

            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${accessToken}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestBody)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            
            if (data.code === 0 && data.messages && data.messages.length > 0) {
                let allContent = [];
                
                for (const message of data.messages) {
                    const content = message.content || '';
                    if (content.trim() && !content.startsWith('RPCError') && content.length >= 5) {
                        allContent.push(content);
                    }
                }
                
                for (const content of allContent) {
                    const imageUrlMatch = content.match(/(https?:\/\/[^\s]+\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?[^\s]*)?)/i);
                    if (imageUrlMatch) {
                        const imageUrl = cleanImageUrl(imageUrlMatch[0]);
                        return formatImageResponse(imageUrl);
                    }
                }
                
                if (allContent.length > 0) {
                    return allContent[allContent.length - 1];
                }
                
                return '🤔 没有收到有效的响应内容，请尝试重新发送您的请求。';
            } else {
                return `❌ API调用失败\n\n错误信息：${data.msg || '未知错误'}`;
            }
        }

        // 清理URL中的转义字符
        function cleanImageUrl(rawUrl) {
            let url = rawUrl;
            
            // 处理转义字符
            url = url.replace(/\\&/g, '&');
            url = url.replace(/\\+$/g, '');
            url = url.replace(/\\/g, '');
            url = url.replace(/["'>\]\)\\,;]+$/, '');
            
            try {
                new URL(url);
                return url;
            } catch (e) {
                return rawUrl;
            }
        }

        // 格式化图片响应
        function formatImageResponse(imageUrl) {
            return `🎉 图片生成成功！

📸 图片链接：${imageUrl}

💡 使用提示：
• 点击链接在新窗口查看图片
• 右键保存图片到本地
• 可以分享链接给其他人

<div style="margin: 15px 0;">
    <a href="${imageUrl}" target="_blank" style="color: #007bff;">🔗 查看图片</a>
</div>`;
        }

        // 添加消息
        function addMessage(text, sender, timestamp = null) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            const time = timestamp || getCurrentTime();

            messageDiv.className = `message ${sender}-message`;
            messageDiv.innerHTML = `
                <div class="message-avatar">${sender === 'user' ? '👤' : '🤖'}</div>
                <div class="message-content">
                    <div class="message-text">${text.replace(/\n/g, '<br>')}</div>
                    <div class="message-time">${time}</div>
                </div>
            `;

            chatMessages.appendChild(messageDiv);
            scrollToBottom();

            const messageData = {
                text: text,
                sender: sender,
                timestamp: time,
                id: Date.now() + Math.random()
            };

            chatHistory.push(messageData);
            saveChatHistory();
        }

        // 显示输入指示器
        function showTypingIndicator() {
            if (document.querySelector('.typing-indicator')) return;

            isTyping = true;
            toggleSendButton();

            const chatMessages = document.getElementById('chatMessages');
            const typingDiv = document.createElement('div');

            typingDiv.className = 'message bot-message typing-message';
            typingDiv.innerHTML = `
                <div class="message-avatar">🤖</div>
                <div class="message-content">
                    <div class="typing-indicator">
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                    </div>
                </div>
            `;

            chatMessages.appendChild(typingDiv);
            scrollToBottom();
        }

        // 隐藏输入指示器
        function hideTypingIndicator() {
            const typingMessage = document.querySelector('.typing-message');
            if (typingMessage) {
                typingMessage.remove();
            }
            isTyping = false;
            toggleSendButton();
        }

        // 清空历史记录
        function clearHistory() {
            if (confirm('确定要清空所有对话历史吗？此操作不可撤销。')) {
                chatHistory = [];
                localStorage.removeItem('cultureImageChatHistory');

                const chatMessages = document.getElementById('chatMessages');
                const welcomeMessage = chatMessages.querySelector('.welcome-message');
                chatMessages.innerHTML = '';
                if (welcomeMessage) {
                    chatMessages.appendChild(welcomeMessage);
                }
            }
        }

        // 导出对话历史
        function exportHistory() {
            if (chatHistory.length === 0) {
                alert('暂无对话记录可导出');
                return;
            }

            let exportText = '贝壳OC文化图片助手 - 对话记录\n';
            exportText += '导出时间: ' + new Date().toLocaleString() + '\n';
            exportText += '='.repeat(50) + '\n\n';

            chatHistory.forEach((message, index) => {
                const sender = message.sender === 'user' ? '用户' : '助手';
                exportText += `${index + 1}. [${message.timestamp}] ${sender}:\n${message.text}\n\n`;
            });

            const blob = new Blob([exportText], { type: 'text/plain;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `文化图片对话记录_${new Date().toISOString().slice(0, 10)}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        // 保存聊天历史
        function saveChatHistory() {
            try {
                localStorage.setItem('cultureImageChatHistory', JSON.stringify(chatHistory));
            } catch (error) {
                console.warn('保存聊天历史失败:', error);
            }
        }

        // 加载聊天历史
        function loadChatHistory() {
            try {
                const saved = localStorage.getItem('cultureImageChatHistory');
                if (saved) {
                    chatHistory = JSON.parse(saved);
                    chatHistory.forEach(message => {
                        addMessage(message.text, message.sender, message.timestamp);
                    });
                }
            } catch (error) {
                console.warn('加载聊天历史失败:', error);
                chatHistory = [];
            }
        }

        // 滚动到底部
        function scrollToBottom() {
            const chatMessages = document.getElementById('chatMessages');
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 获取当前时间
        function getCurrentTime() {
            const now = new Date();
            return now.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    </script>
</body>

</html>